import pandas as pd
from pathlib import Path


class WordDataLoader:
    def __init__(self, excel_path):
        self.excel_path = Path(excel_path)
        self.data = None
        self.load_data()

    def load_data(self):
        if self.excel_path.exists():
            try:
                self.data = pd.read_excel(self.excel_path)
                # 确保必要的列存在
                required_columns = ['word', 'phonetic', 'definition', 'status']
                for col in required_columns:
                    if col not in self.data.columns:
                        if col == 'status':
                            self.data['status'] = 'unlearned'  # 默认状态
                        else:
                            raise ValueError(f"Missing required column: {col}")
            except Exception as e:
                raise ValueError(f"Error loading Excel file: {str(e)}")
        else:
            raise FileNotFoundError(f"Excel file not found: {self.excel_path}")

    def get_page_data(self, page, per_page=10, filter_status='all'):
        if self.data is None:
            return []

        # 应用筛选
        if filter_status == 'learned':
            filtered_data = self.data[self.data['status'] == 'learned']
        elif filter_status == 'unlearned':
            filtered_data = self.data[self.data['status'] == 'unlearned']
        else:  # 'all'
            filtered_data = self.data.copy()

        # 分页
        start_idx = (page - 1) * per_page
        end_idx = start_idx + per_page
        return filtered_data.iloc[start_idx:end_idx].to_dict('records')

    def get_total_pages(self, per_page=10, filter_status='all'):
        if self.data is None:
            return 0

        if filter_status == 'learned':
            total = len(self.data[self.data['status'] == 'learned'])
        elif filter_status == 'unlearned':
            total = len(self.data[self.data['status'] == 'unlearned'])
        else:  # 'all'
            total = len(self.data)

        return (total + per_page - 1) // per_page

    def update_word_status(self, word, status):
        if self.data is not None and word in self.data['word'].values:
            self.data.loc[self.data['word'] == word, 'status'] = status
            self.save_data()

    def save_data(self):
        self.data.to_excel(self.excel_path, index=False)